#include "FaceExtract.h"
#define RATE 10

FaceExtract::FaceExtract(std::string path) {
	ErrorFlag = false;
	//配置文件，一定要有
	if (!hc.load(path)) {
		ErrorFlag = true;
		printf("Failed to load Haar cascade\n");
	}
}

FaceExtract::~FaceExtract() {

}

bool FaceExtract::HasError() {
	return ErrorFlag;
}

cv::Mat FaceExtract::GiveFace() {
	cv::Mat tmp = FACES.front();
	FACES.pop();
	return tmp;
}

FaceExtract::operator bool() {
	return !FACES.empty();
}

bool FaceExtract::AnalyzeFrame(cv::UMat &frame) {

	if (frame.empty()) {
		ErrorFlag = true;
		std::cout << "Not find frame" << std::endl;
		return false;
	}
    cv::UMat tmp = frame;
	//cvtColor(frame, tmp, CV_BGR2GRAY);
    //cv::equalizeHist(tmp, tmp);
	std::vector<cv::Rect> faces;
	faces.clear();

	hc.detectMultiScale(tmp, faces, 1.1, 2, cv::CASCADE_SCALE_IMAGE, cv::Size(15, 15));

	for (size_t i = 0; i < faces.size(); i++) {
		cv::Rect ROI;
		ROI.x = (faces[i].x - 20 > 0) ? faces[i].x - 20 : 0;
		ROI.width = (faces[i].width + 40 < tmp.cols) ? faces[i].width + 40 : tmp.cols;
		ROI.y = (faces[i].y - 25 > 0) ? faces[i].y - 25 : 0;
		ROI.height = (faces[i].height + 50 < tmp.rows) ? faces[i].width + 50 : tmp.rows;
        
        if ((ROI.x+ROI.width)>tmp.cols) {
            ROI.width = tmp.cols - ROI.x;
        }
        if ((ROI.y+ROI.height)>tmp.rows) {
            ROI.height = tmp.rows - ROI.y;
        }
        
        //debug 开始
        //std::cout<<"ROI:"<<"x="<<ROI.x<<" y="<<ROI.y<<" width="<<ROI.width<<
        //" height="<<ROI.height<<" row="<<frame.rows<<" col="<<frame.cols<<std::endl;
        //debug 结束
        
		cv::Mat imgROI;
		try {
			imgROI = frame(ROI).getMat(cv::ACCESS_RW);
            //cv::imshow("Detect", imgROI);
		}
		catch (cv::Exception & ex) {
			std::cout << "ROI:" << ex.what();
			return false;
		}
        
        
		FACES.push(imgROI);
	}

	return true;
}
